package com.web.dao.impl;

import com.web.dao.StudentDAO;
import com.web.entity.Student;
import com.web.util.JDBCUtils;

import java.util.List;

public class StudentDAOimpl implements StudentDAO {
    @Override
    public List<Student> selectAllStudents() {
        List<Student> students = JDBCUtils.query(Student.class, "select * from student");
        for(Student stu : students){
            System.out.println(stu);
        }
        return students;
    }

    @Override
    public List<Student> selectStudentByName(String name) {
        List<Student> students = JDBCUtils.query(Student.class, "select * from student where name like ?", "%"+name+"%");
        for(Student stu : students){
            System.out.println(stu);
        }
        return students;
    }

    @Override
    public Student selectStudentById(int id) {
        String sql = "SELECT * FROM student WHERE id = ?";
        List<Student> students = JDBCUtils.query(Student.class, sql, id);
        if (students != null && !students.isEmpty()) {
            return students.get(0); // 返回第一个学生对象
        }
        return null; // 如果没有找到，返回 null
    }

    @Override
    public int insertStudent(Student student) {
        String sql = "INSERT INTO student (name, age, gender, idcard, address) VALUES (?, ?, ?, ?, ?)";
        return JDBCUtils.update(sql, student.getName(), student.getAge(),
                student.getGender(), student.getIdcard(), student.getAddress());
    }

    @Override
    public void updateStudentById(Student student) {
        String sql = "UPDATE student SET name=?, age=?, gender=?, idcard=?, address=? WHERE id=?";
        int rows = JDBCUtils.update(sql, student.getName(), student.getAge(), student.getGender(), student.getIdcard(), student.getAddress(), student.getId());
        if (rows > 0) {
            System.out.println("更新成功！");
        } else {
            System.out.println("更新失败！");
        }

    }

    @Override
    public void deleteStudentById(Integer id) {
        String sql = "DELETE FROM student WHERE id=?";
        int rows = JDBCUtils.update(sql, id);
        if (rows > 0) {
            System.out.println("删除成功！");
        } else {
            System.out.println("删除失败！");
        }

    }

    @Override
    public int selectStudentsCount() {
        return JDBCUtils.queryCount("select count(*) from student");
    }

    @Override
    public List<Student> selectStudentsPage(int start, int len) {
        return JDBCUtils.query(Student.class, "select * from student limit ?,?", start, len);
    }


}

